$(function () {
    function renderForm() {
        layui.use('form', function () {
            let form = layui.form;
            form.render();
        })
    }

    function productSelect() {
        let category = $('#category option:selected');
        $.get({
            url: 'queryProductByCategory', data: {
                "category": category.text()
            }, async: false, success: function (data) {
                let product = $('#product');
                product.children().remove();
                for (let i = 0; i < data.length; i++) {
                    product.append("<option value='" + i + "'>" + data[i].name + "</option>")
                }
                product.append("<option  value='-1'>" + "添加系列" + "</option>")
                renderForm();
            },
            error:function (){
                let product = $('#product');
                product.children().remove();
                product.append("<option  value='-1'>" + "添加系列" + "</option>")
            }
        })
    }

    layui.use('form', function () {
        let form = layui.form;
        let layer = layui.layer;
        //动态添加下拉框
        $.get({
            url: "/selectAllCategory", //请求路径，和form中action属性作用一样
            // dataType:"text",// Java 端返回的数据类型
            async: false, success: function (data) {
                let category = $('#category');
                for (let i = 0; i < data.length; i++) {
                    $('#category').append("<option value='" + i + "'>" + data[i].name + "</option>")
                }
                category.append("<option value='-1'>" + "添加类别" + "</option>")
                renderForm();
            }
        });
        //选择图片展示图片
        let uploadImg = $('#uploadImg');
        uploadImg.change(function () {
            let imageName = uploadImg.val();
            let suffixIndex = imageName.lastIndexOf(".");
            let suffix = imageName.substring(suffixIndex + 1).toLowerCase();
            if (suffix !== "bmp" && suffix !== "jpg" && suffix !== "jpeg" && suffix !== "png" && suffix !== "gif") {
                uploadImg.val(null);
                let p = '<p style="color: red">请选择图片</p>'
                uploadImg.after(p);
            } else {
                uploadImg.next('p').remove();
                let fileReader = new FileReader();
                fileReader.readAsDataURL(this.files[0]);
                fileReader.onload = function () {
                    $('.upload').after('<img id="#image" style="width: 100px;height: 100px" alt="" src='+fileReader.result+' >')

                }
            }

        });

        productSelect();
        //下拉列表联动
        form.on('submit',function (obj){
            let name = $('#name').val();
            let product =  $('#product').find('option:selected').text();
            let category = $('#category').find('option:selected').text();
            let image = $('#uploadImg').val();
            let version = $('#version').val();
            let color = $('#color').val();
            let price = $('#price').val();
            let count = $('#count').val();

            let trueImage = $('#uploadImg').get(0).files[0];
            // let form = $('#updateItemFoem');
            let fileParam = new FormData();
            fileParam.append('file',trueImage);
            fileParam.append('name',name);
            fileParam.append('product',product);
            fileParam.append('category',category);
            fileParam.append('image',image);
            fileParam.append('version',version);
            fileParam.append('color',color);
            fileParam.append('price',price);
            fileParam.append('count',count);
            $.ajax({
                type    : 'post',
                url     : '/addItems',
                data:  fileParam ,
                processData : false, //必须false才会自动加上正确的Content-Type
                contentType : false ,//必须false才会避开jQuery对 formdata 的默认处理
                error: function (data){
                    console.log('错了');
                },
                success: function (data) {
                    if(data==="success") {
                        window.parent.location.reload();
                        let index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    }
                }
            });
            return false;
        });
        //下拉列表联动

        form.on('select(selectCategory)', function (data) {
            //如果是添加则将select改变为input
            if(data.value==="-1"){
                $('#divCategory').hide();
                let input = " <div  class=\"layui-input-block\">";
                input+=  "<input id=\"inputCategory\" type=\"text\" lay-verify=\"required\" placeholder=\"请输入产品类别\"\n" +
                    "class=\"layui-input\">";
                input+="</div>"
                $('#labelCategory').after(input);
                document.getElementById("inputCategory").focus();
                $('#inputCategory').blur(function (){
                    let inputCategory = $('#inputCategory');
                    let category = inputCategory.val();
                    // 删除input
                    $('#divCategory').show();
                    inputCategory.parent().remove();
                    inputCategory.remove();
                    $.get({
                        url:"addCategory",
                        data:{"name":category},
                        success:function (data){

                            let option = $('#category option');
                            let length = option.length;
                            let i =length-1;
                            //将节点添加到最后一个
                            $("#category option[value='-1']").before("<option value='" + i + "'>" + category + "</option>");
                            let newOptions = $('#category option');
                            for(let i = 0;i<length;i++){
                                let text = newOptions[i].text;
                                if(category === text) {
                                    $('.layui-select-title').eq(0).children('input').val(category);
                                    newOptions[i].selected=true;
                                    newOptions[i].autocomplete="off";
                                    break;
                                }
                            }
                            // renderForm();
                            // productSelect();
                        }
                    })
                })

            }
            productSelect();
        });


        form.on('select(selectProduct)', function (data) {
            //如果是添加则将select改变为input
            if(data.value==="-1"){
                $('#divProduct').hide();
                let input = " <div  class=\"layui-input-block\">";
                input+=  "<input id=\"inputProduct\" type=\"text\" lay-verify=\"required\" placeholder=\"请输入产品类别\"\n" +
                    "class=\"layui-input\">";
                input+="</div>"
                $('#labelProduct').after(input);
                document.getElementById("inputProduct").focus();
                $('#inputProduct').blur(function (){
                    let inputProduct = $('#inputProduct');
                    let product = inputProduct.val();
                    // 删除input
                    $('#divProduct').show();
                    inputProduct.parent().remove();
                    inputProduct.remove();
                    $.get({
                        url:"addProduct",
                        data:{
                            "name":product,
                            "category": $('#category option:selected').text()
                        },
                        success:function (data){

                            let option = $('#product option');
                            let length = option.length;
                            let i =length-1;
                            //将节点添加到最后一个
                            $("#product option[value='-1']").before("<option value='" + i + "'>" + product + "</option>");
                            let newOptions = $('#product option');
                            for(let i = 0;i<length;i++){
                                let text = newOptions[i].text;
                                if(product === text) {
                                    $('.layui-select-title').eq(1).children('input').val(product);
                                    newOptions[i].selected=true;
                                    newOptions[i].autocomplete="off";
                                    break;
                                }
                            }
                        }
                    })
                })

            }

        });
    });
})